#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>


 struct ListNode {
     int val;
     struct ListNode *next;
};
 struct ListNode* removeElements(struct ListNode* head, int val) {
     if (head == NULL) {
         return NULL;
     }
     while (head->val == val && head->next != NULL) {
         head = head->next;
     }
     if (head->next == NULL && head->val == val) {
         free(head);
         head = NULL;
         return head;
     }
     struct ListNode* phead = head;
     struct ListNode* mod = head;
     while (phead->next != NULL) {
         if (phead->val == val) {
             mod->next = phead->next;
             free(phead);
             phead = mod->next;
         }
         else {
             mod = phead;
             phead = phead->next;
         }

     }

     if (phead->val == val) {
         mod->next = phead->next;
         free(phead);
         phead = NULL;
     }
     return head;
 }